#
# "@(#) $Id: M3U.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
# handle .m3u files for radio stations 
# this very poor implementation but will work well for M3U streams 
# like icecast

import socket, urllib2, re
#Socket Timeout (seconds)
timeout = 60
socket.setdefaulttimeout( timeout)

def fetchAndParseM3U(url):
	req = urllib2.Request(url)
	fh=urllib2.urlopen(req)
	if fh:
		plist=fh.read()
		if plist:
			#urllib2.close()
			return parseM3U(plist)
	return None


def parseM3U(pls):
	flags = re.MULTILINE | re.IGNORECASE
	#p = re.search(r"(.+)",pls,flags)
	#print p.group(),"BEFORE FOR"
	lines=pls.splitlines()
	#print lines, "SPLITTING LINES"
	streams = []
	for line in lines:
		p = re.search(r"http://(.+)",line,flags)
		if p:
			streams.append(p.group())
	return streams

if __name__=='__main__':
	print fetchAndParseM3U("http://dir.xiph.org/listen.php?pid=2901325&file=listen.m3u")

